package com.example01.demo.utils;

import lombok.Getter;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MybatisUtils {
    @Getter
    private static SqlSessionFactory factory = null;
    private static final String RESOURCE = "mybatis-config.xml";
    private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();

    static {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        try {
            factory = sqlSessionFactoryBuilder.build(Resources.getResourceAsReader(RESOURCE));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSQlSession(Boolean isAutoCommit) {
        SqlSession sqlSession = THREAD_LOCAL.get();
        if (sqlSession == null){
            sqlSession = factory.openSession(isAutoCommit);
            THREAD_LOCAL.set(sqlSession);
        }
        return sqlSession;
    }

    public static SqlSession getSqlSession() {
        return getSQlSession(true);
    }

    public static <T> T getMapper(Class<T> clazz) {
        return getSqlSession().getMapper(clazz);
    }

}
